use std::fs;

fn read_lines(file_name: &str) -> Vec<String> {
    let contents = fs::read_to_string(file_name).unwrap();
    let lines = contents
        .trim()
        .replace("\r", "")
        .split("\n")
        .map(|x| x.to_owned())
        .collect::<Vec<_>>();
    return lines;
}

fn str_to_id(line: &str) -> usize {
    let bin_str = line
        .replace("F", "0")
        .replace("B", "1")
        .replace("R", "1")
        .replace("L", "0");

    let id = usize::from_str_radix(&bin_str, 2).unwrap();
    return id;
}

fn part1() {
    let lines = read_lines("input.txt");
    //println!("{:?}", lines);
    let mut max_id = 0;
    for line in &lines {
        let id = str_to_id(line);
        if max_id < id {
            max_id = id;
        }
    }
    println!("Part1:");
    println!("Max id = {}", max_id);
}

fn part2() {
    let lines = read_lines("input.txt");
    let mut max_id = 0;
    let mut vec = vec![0; 1 << 10];
    for line in &lines {
        let id = str_to_id(line);
        vec[id] = 1;
    }
    println!("Part2");
    for (i, value) in vec.iter().enumerate() {
        if value == &0 {
            println!("Missing seat: {}", i);
        }
    }
}

#[test]
fn convert_to_bin_test() {
    assert_eq!(str_to_id("BFFFBBFRRR"), 567);
    assert_eq!(str_to_id("FFFBBBFRRR"), 119);
    assert_eq!(str_to_id("BBFFBBFRLL"), 820);
    assert!(str_to_id("BFBBBBFRLL") >= 0);
}

fn main() {
    part1();
    part2();
}
